<template>
  <a-modal
    v-model="importVisible"
    title="导入"
    :footer="null"
    :width="800"
    :maskClosable="false"
    :destroyOnClose="true"
    @cancel="handleCancel"
  >
    <div>
      <a-steps :current="current">
        <a-step v-for="item in steps" :key="item.title" :title="item.title" />
      </a-steps>
      <div class="steps-content">
        <template v-if="current === 0">
          <a-row type="flex" justify="space-around" align="middle">
            <a-col :span="2">
              <a-icon type="cloud-download" style="font-size: 40px; color: #1890ff" />
            </a-col>
            <a-col :span="20">
              <a-row>
                <a-col :span="20"><span class="title">填写导入的商品信息</span></a-col>
              </a-row>
              <a-row>
                <a-col :span="20"
                  ><span class="tips">请按照数据模板格式准备导入数据, 模板中表头名称不可更改, 表头不可删除</span></a-col
                >
              </a-row>
              <a-row>
                <a-col :span="20"
                  ><a
                    href="https://myxp.oss-cn-hangzhou.aliyuncs.com/Static/%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xls"
                    class="pd"
                    >下载模板</a
                  ></a-col
                >
              </a-row>
            </a-col>
          </a-row>
          <a-row type="flex" justify="space-around" align="middle">
            <a-col :span="2">
              <a-icon type="cloud-upload" style="font-size: 40px; color: #1890ff" />
            </a-col>
            <a-col :span="20">
              <a-row>
                <a-col :span="20"><span class="title">选择填好的商品信息表</span></a-col>
              </a-row>
              <a-row>
                <a-col :span="20"
                  ><span class="tips">文件后缀名必须为xlxs(即Excel文件), 单次最多导入2000行</span></a-col
                >
              </a-row>
              <a-row>
                <a-col :span="20"
                  ><a-upload :before-upload="beforeUpload" :remove="handleRemove" :file-list="fileList"
                    ><a class="pd">选择文件</a></a-upload
                  ></a-col
                >
              </a-row>
            </a-col>
          </a-row>
        </template>
        <template v-if="current === 1">
          <a-row type="flex" justify="space-around" align="middle">
            <a-col :span="22">
              <a-result>
                <template #title>
                  <span style="font-size: 16px">正在执行导入...</span>
                </template>
                <template #icon>
                  <a-icon type="loading" />
                </template>
              </a-result>
            </a-col>
          </a-row>
        </template>
        <template v-if="current === 2">
          <a-row type="flex" justify="space-around" align="middle">
            <a-col :span="22">
              <a-result :status="status">
                <template #title>
                  <p style="font-size: 16px; color: red" v-if="res.key === 'timeout' || res.key === 'error'"
                    >导入失败: {{ res.title }}</p
                  >
                  <p style="font-size: 16px" v-else
                    >导入成功<span style="color: red;padding:0 3px;font-weight:600">{{ res.succ }}</span
                    >条,失败<span style="color: red;padding:0 3px;font-weight:600">{{ res.fail }}</span>条</p
                  >
                  <p style="font-size: 14px" v-if="res.fail > 0"><a  @click="downFail('失败的商品')">下载导入失败的Excel</a></p>
                </template>
              </a-result>
            </a-col>
          </a-row>
        </template>
      </div>
      <div class="steps-action">
        <a-button
          v-if="current === 0"
          type="primary"
          @click="handleUpload"
          :disabled="fileList.length === 0"
          :loading="uploading"
        >
          上传
        </a-button>
        <a-button v-if="current === 2" type="primary" @click="handleCancel"> 确定 </a-button>
      </div>
    </div>
  </a-modal>
</template>
<script>
import { randomUUID } from '@/utils/util'
import { getAction, uploadAction, downFile } from '@/api/manage'
export default {
  components: {},
  name: 'SignProImport',
  data() {
    return {
      fileList: [],
      uploading: false,
      importVisible:false,
      taskId: '',
      current: 0,
      timer: '',
      timeout: 0,
      status: '',
      actId: '',
      orgId: '',
      res: {
        succ: 0,
        fail: 0,
      },
      isTimeout: false,
      steps: [
        {
          title: '上传文件',
        },
        {
          title: '执行导入',
        },
        {
          title: '导入完成',
        },
      ],
    }
  },
  methods: {
    downFail(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { taskId: this.taskId }
      downFile('/marketing/posGoodsSaleRule/exportFailXls', param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleCancel(){
      this.uploading = false
      this.importVisible = false
      this.current = 0
      this.fileList = []
      clearInterval(this.timer)
    },
    init(actId, orgId) {
      console.log('actId=', actId, ',org=', orgId)
      this.actId = actId
      this.orgId = orgId
      this.importVisible = true
    },
    handleRemove(file) {
      this.fileList = []
    },
    beforeUpload(file) {
      console.log(file.type)
      const isExcel = file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('文件格式不正确')
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('文件不能大于2MB!')
        return false
      }

      this.fileList = [file]
      return false
    },
    handleUpload() {
      this.uploading = true
      this.current = 1
      this.handleExecute()
    },
    get() {
      console.log('get result')
      this.timeout++
      if (this.timeout === 150) {
        //5分钟
        this.isTimeout = true
        clearInterval(this.timer)
        this.handleResult('timeout')
      } else {
        let that = this
        getAction('/marketing/posGoodsSaleRule/getImportResult', { taskId: this.taskId })
          .then((res) => {
            if (res.code === 200) {
              this.handleResult('ok', res)
              this.$emit('ok')
            }
            if (res.code === 500) {
              this.handleResult('error', res)
            }
          }).finally(()=>{
            clearInterval(this.timer)
          })
      }
    },
    handleResult(res, resultObj) {
      this.current = 2
      if (res === 'ok') {
        this.status = 'success'
        this.res = {
          title: '导入成功',
          succ: resultObj.result.succ,
          fail: resultObj.result.fail,
          key: res,
        }
      } else if (res === 'error') {
        this.status = 'warning'
        this.res = {
          title: resultObj.message,
          msg: '',
          key: res,
        }
      } else if (res === 'timeout') {
        this.status = 'warning'
        this.res = {
          title: '查询结果超时',
          msg: '',
          key: res,
        }
      }
    },
    handleExecute() {
      console.log(this.fileList[0])
      this.taskId = randomUUID()
      const formData = new FormData()
      formData.append('file', this.fileList[0])
      formData.append('taskId', this.taskId)
      formData.append('actId', this.actId)
      formData.append('orgId', this.orgId)

      uploadAction('/marketing/posGoodsSaleRule/importExcel', formData).then((res) => {
        console.log(res)
        if (!res.success) {
          this.handleResult('error', res)
        }
      })

      this.timer = setInterval(this.get, 2000)
    },
  },
}
</script>
<style lang="less" scoped>
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  min-height: 200px;
  text-align: left;
  padding-left: 20px;
  padding-top: 20px;

  .pd {
    padding: 10px 0;
    display: inline-block;
  }
  .title {
    font-weight: 600;
  }

  .tips {
    color: #999;
  }
}

.steps-action {
  margin-top: 24px;
  text-align: right;
}
</style>
